// 默认服务器地址
// const DEFAULT_BASE_URL = 'https://mom.aiiiss.com:5555/api/';
// const DEFAULT_BASE_URL = 'http://192.168.3.6:1010/api/';
const DEFAULT_BASE_URL = 'http://192.168.3.9:1010/api/';

import AsyncStorage from '@react-native-async-storage/async-storage';
import { getAppVersion } from '../utils/version';

let token: string | null = null;
let baseUrl: string | null = null;

// 获取服务器地址
export const getBaseUrl = async (): Promise<string> => {
  if (baseUrl) return baseUrl;
  const storedUrl = await AsyncStorage.getItem('baseUrl');
  baseUrl = storedUrl || DEFAULT_BASE_URL;
  return baseUrl;
};

// 设置服务器地址
export const setBaseUrl = async (url: string) => {
  // 确保URL格式正确
  let formattedUrl = url.trim();
  if (!formattedUrl.endsWith('/')) {
    formattedUrl += '/';
  }
  if (!formattedUrl.endsWith('api/')) {
    formattedUrl += 'api/';
  }

  baseUrl = formattedUrl;
  await AsyncStorage.setItem('baseUrl', formattedUrl);
  console.log('服务器地址已更新为:', formattedUrl);
};

export const setToken = async (t: string) => {
  token = t;
  await AsyncStorage.setItem('token', t);
};

export const getToken = async () => {
  if (token) return token;
  token = await AsyncStorage.getItem('token');
  return token;
};

export async function request(path: string, options: RequestInit = {}) {
  const currentBaseUrl = await getBaseUrl();
  const url = currentBaseUrl + path.replace(/^\//, '');
  const t = await getToken();
  const appVersion = getAppVersion();
  const headers = {
    'Content-Type': 'application/json',
    'version': appVersion,
    ...(options.headers || {}),
    ...(t ? { token: t } : {}),
  };
  console.log('请求URL:', url);
  // console.log('请求headers:', headers);
  // console.log('应用版本号:', appVersion);
  const res = await fetch(url, { ...options, headers });
  const data = await res.json();
  if (!res.ok) throw new Error(data.msg || '网络请求失败');
  return data;
} 